package com.sise.dubbo.redislock.service;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁的守护线程
 *
 * @author idea
 * @data 2019/2/2
 */
@Data
public class LockDaemonThread implements Runnable {

    private String lockKey;

    /**
     * 锁的安全时限数值（当锁到达接近过期时间的时候，需要延长实现）
     */
    private Integer LOCK_MIN_MILLISECOND=2;

    private RedisTemplate<String, Object> redisTemplate;

    public LockDaemonThread(String key,RedisTemplate<String, ? extends Object> redisTemplate) {
        this.lockKey=key;
        this.redisTemplate= (RedisTemplate<String, Object>) redisTemplate;
    }

    @Override
    public void run() {
        String key = getLockKey();
        if (StringUtils.isEmpty(lockKey)) {
            return;
        } else {
            System.out.println("守护线程！");
            while (true) {
                //获取锁的有效时间，0表示永久有效
                Long expireTime = redisTemplate.getExpire(key, TimeUnit.SECONDS);
                //给锁延时操作
                if(expireTime<LOCK_MIN_MILLISECOND){
                    redisTemplate.expire(key,10,TimeUnit.SECONDS);
                }
                try {
                    //暂停一秒钟，测试使用
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
